//
//  LevelManager.m
//  Project 5
//
//  Created by Nguyen Tan Loc on 6/20/13.
//  Copyright (c) 2013 Nguyen Tan Loc. All rights reserved.
//

#import "LevelManager.h"
#import "XMLDefine.h"

@implementation LevelManager

static LevelManager *m_Instance = nil;

+(LevelManager *) shareLevelManager
{
    if (m_Instance == nil)
        m_Instance = [[LevelManager alloc] init];
    return m_Instance;
}

-(id) init
{
    if (self = [super init])
    {
        mListLevel =[[NSArray alloc] initWithObjects:
                     @"Level_Template",
                      nil];
    }
    
    return self;
}

-(void) setCurrentLevelt:(int)currentLevel
{
    mCurrentLevel = currentLevel;
}

-(void) loadCurrentLevel
{
    if (mCurrentLevel > mListLevel.count)
    {
        CCLOG(@"level is out of range");
    }
    
    NSString *path = [mListLevel objectAtIndex:mCurrentLevel];
    [self loadLevel:path];
}

-(void) loadLevel:(NSString *)path
{
    
    NSString *filePath = [[NSBundle mainBundle] pathForResource:path ofType:@"xml"];
    NSData *xmlData = [[NSMutableData alloc] initWithContentsOfFile:filePath];
    NSError *error;
    
    mDataXMLDocument = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:&error];
    
    if (mDataXMLDocument == nil)
    {
        // process here
        CCLOG(@"document = nil");
    }
    
    [xmlData release];
    xmlData = nil;
}

-(Path *) getPath
{
    Path *path = [[[Path alloc] init] autorelease];
    
    NSArray *listPath = [mDataXMLDocument.rootElement elementsForName:XML_LINE_PATH];
    for (GDataXMLElement *ePath in listPath)
    {
        NSArray *listNode = [ePath elementsForName:XML_NODE];
        for (GDataXMLElement *eNode in listNode)
        {
            int x = [[[eNode attributeForName:XML_X] stringValue] intValue];
            int y = [[[eNode attributeForName:XML_Y] stringValue] intValue];
            
            Node *node = [[Node alloc] init];
            [node setPosition:ccp(x, y)];
            [path pushNode:node];
            [node release];
        }
    }
    
    [path arrangeChild];
    return path;
}

//-(void) loadComboInfo
//{
//    NSMutableArray *listCombo = [[[NSMutableArray alloc] init] autorelease];
//    NSArray *listLevelInfo = [mDataXMLDocument.rootElement elementsForName:XML_LEVEL];
//    for (GDataXMLElement *eLevel in listLevelInfo)
//    {
//        NSArray *listComboInfo = [eLevel elementsForName:XML_COMBO];
//        for (GDataXMLElement *eCombo in listComboInfo)
//        {
//            int score = [[[eCombo attributeForName:XML_SCORE] stringValue] intValue];
//            int item = [[[eCombo attributeForName:XML_ITEM] stringValue] intValue];
//            [listCombo addObject:[NSNumber numberWithInt:score]];
//            [listCombo addObject:[NSNumber numberWithInt:item]];
//        }
//    }
//    
//    [[Combo shareCombo] setListComboInfo:listCombo];
//}


-(void) removeData
{
    [mDataXMLDocument release];
    mDataXMLDocument = nil;
}

@end


